package com.uit.se6.customui.android.navigation.accordion;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.uit.se6.customui.R;

public class ToggleImageButton extends ImageView {
	private int img_on;
	private int img_off;

	private boolean visible = false;// default invisible

	public ToggleImageButton(Context context, AttributeSet attrs) {
		super(context, attrs);

		// get attributes
		if (attrs != null) {
			try {
				TypedArray ta = context.obtainStyledAttributes(attrs,
						R.styleable.Accordion_ToggleImageView, 0, 0);
				img_on = ta.getResourceId(
						R.styleable.Accordion_ToggleImageView_img_on, 0);
				img_off = ta.getResourceId(
						R.styleable.Accordion_ToggleImageView_img_off, 0);
				ta.recycle();

				setImageResource(img_off);
			} catch (Exception e) {
				Log.e(this.getClass().getName(), e.toString());
			}
		}
	}

	public ToggleImageButton(Context context) {
		super(context);

		// default
		img_on = R.drawable.accordion_royalwhite_down;
		img_off = R.drawable.accordion_royalwhite_up;
		setImageResource(img_off);
	}

	@Override
	public void setOnClickListener(final OnClickListener l) {
		// recreate a new listener
		OnClickListener wrappingListener = new OnClickListener() {

			public void onClick(View v) {
				visible = !visible;
				handleState(visible);
				l.onClick(v);
			}
		};

		super.setOnClickListener(wrappingListener);
	}

	public void setImageOnResource(int resource) {
		img_on = resource;
	}

	public void setImageOffResource(int resource) {
		img_off = resource;
	}

	public void setState(boolean visible) {
		this.visible = visible;
		handleState(this.visible);
	}

	private void handleState(boolean visible) {
		if (visible) {
			setImageResource(img_on);
		} else {
			setImageResource(img_off);
		}
	}
}
